<template>
  <!-- 商品-商品规格 -->
  <div>
    <Card :bordered="false" dis-hover class="ivu-mts">
      <div class="new_card_pd">
        <!-- 筛选条件 -->
        <Form
            inline
            ref="artFrom"
            :model="artFrom"
            :label-width="labelWidth"
            :label-position="labelPosition"
            class="tabform"
            @submit.native.prevent
        >
          <Row :gutter="24" type="flex" justify="end">
            <Col span="24" class="ivu-text-left">
				<FormItem :label="$t('page.customer.customer_name')+'：'">
				  <Input
				      v-model="artFrom.company"
				      placeholder=""
				      class="input-add"
				  ></Input>
				</FormItem>
              <FormItem :label="$t('page.customer.email')+'：'">
                <Input
                    v-model="artFrom.email"
                    placeholder=""
                    class="input-add"
                ></Input>
				        <Button type="primary" @click="userSearchs" icon="md-search"></Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
    </Card>
    <!-- 相关操作 -->
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button
          class="mr20"
          type="primary"
          @click="addAttr"
      >{{$t('page.customer.add_customer')}}</Button
      >
	  <Button
	      class="mr20"
	      type="primary"
	      @click="exportStock"
	  >{{$t('page.customer.export')}}</Button>
      <!-- 商品规格表格 -->
      <Table
          class="mt25"
          ref="selection"
          :columns="columns4"
          :data="tableList"
          :loading="loading"
          highlight-row
          :no-data-text="$t('page.product.no_data')"
          :no-filtered-data-text="$t('page.product.no_filtering')"
      >
        <template slot-scope="{ row }" slot="attr_value">
          <span
              v-for="(item, index) in row.attr_value"
              :key="index"
              v-text="item"
              style="display: block"
          ></span>
        </template>
		<template slot-scope="{ row, index }" slot="created_at">
		  {{ formatTimeNative(row.created_at) }} <!-- 调用格式化方法 -->
		</template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="edit(row)">{{$t('page.customer.edit')}}</a>
          <Divider type="vertical" />
		  <a @click="openModal(row)">{{$t('page.customer.detail')}}</a>
		  <Divider type="vertical" />
          <a @click="del(row, 'Remove customer', index)">{{$t('page.product.remove')}}</a>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page
            :total="total"
            :current="artFrom.page"
            @on-change="pageChange"
            :page-size="artFrom.limit"
        />
      </div>
    </Card>
    <add-customer 
	ref="addattr" 
	:languagesList="languagesList" 
	:statesList="statesList" 
	:tagsList="tagsList" 
	:countryList="countryList" 
	@getList="userSearchs" 
	@fetchTags="getTagsListApi"
	@countryChanged="loadStates">
	</add-customer>
	<customer-info ref="customerInfo"  :visible.sync="modalVisible"></customer-info>
  </div>
</template>

<script>
import { mapState } from "vuex";
import addCustomer from "../components/addCustomer";
import customerInfo from '../components/customerInfo';
import { storeCustomerListApi,languagesListApi,statesListApi,countryListApi,tagsListApi,exportStoreCustomerList } from "@/api/storeCustomer";
export default {
  name: "productAttr",
  components: { addCustomer,customerInfo },
  
  data() {
    return {
      loading: false,
	  modalVisible: false,
	  languagesList:[],
	  statesList:[],
	  countryList:[],
	  tagsList:[],
      artFrom: {
        page: 1,
        limit: 10,
        name: "",
		company:"",
		phone: "",
		country_id:0,
		lang:'',
      },
  //     columns4: [
  //       {
  //         title: "Customer Name",
  //         key: "company",
  //         minWidth: 150,
  //       },
  //       {
  //         title: "Location",
  //         key: "state",
  //         minWidth: 300,
  //       },
		// {
		//   title: "Email",
		//   key: "email",
		//   minWidth: 300,
		// },
		// {
		//   title: "Tag",
		//   key: "tags_name",
		//   minWidth: 300,
		// },
		// {
		//   title: "Orders",
		//   key: "order_count",
		//   minWidth: 300,
		// },
		// {
		//   title: "Amount Spent",
		//   key: "amount_spent",
		//   minWidth: 300,
		// },
		// {
		//   title: "Created At",
		//   slot: "created_at",
		//   minWidth: 300,
		// },
  //       {
  //         title: "Operate",
  //         slot: "action",
  //         fixed: "right",
  //         width: 120,
  //       },
  //     ],
      tableList: [],
      total: 0
    };
  },
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
    ...mapState("admin/order", ["orderChartType"]),
    labelWidth() {
      return this.isMobile ? undefined : 130;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
	columns4(){
		return [
		  {
		    title: $t('page.customer.customer_name'),
		    key: "company",
		    minWidth: 150,
		  },
		  {
		    title: $t('page.customer.location'),
		    key: "state",
		    minWidth: 300,
		  },
				{
				  title: $t('page.customer.email'),
				  key: "email",
				  minWidth: 300,
				},
				{
				  title: $t('page.customer.tag'),
				  key: "tags_name",
				  minWidth: 300,
				},
				{
				  title: $t('page.customer.orders'),
				  key: "order_count",
				  minWidth: 300,
				},
				{
				  title: $t('page.customer.amount_spent'),
				  key: "amount_spent",
				  minWidth: 300,
				},
				{
				  title: $t('page.customer.created_at'),
				  slot: "created_at",
				  minWidth: 300,
				},
		  {
		    title: $t('page.customer.operate'),
		    slot: "action",
		    fixed: "right",
		    width: 160,
		  },
		]
	}
  },
  created() {
    this.getDataList();
	this.getLanguagesList();
	this.getStatesList();
	this.getCountryList();
	this.getTagsListApi();
	
  },
  watch: {
    '$i18n.locale'(newLocale) {
      this.fetchData();
    }
  },
  mounted() {
  	this.getToken();
  },
  methods: {
	  fetchData(){
		  let lang = this.getCurrentLanguage()
		  this.artFrom.lang = lang
		  this.getLanguagesList();
		  this.getStatesList();
		  this.getCountryList();
	  },
	  getToken() {
	    this.header["Authori-zation"] = "Bearer " + util.cookies.get("token");
	  },
		openModal(row) {
	        this.modalVisible = true;
			this.$refs.customerInfo.getIofo(row);
	    },
	  async loadStates(countryId){
		  this.artFrom.country_id = countryId
		  statesListApi(this.artFrom).then((res) => {
		  this.statesList = res.data.list;
		  }).catch((err)=>{ 
		  	this.$Message.error(err.msg);
		  })
	  },
	  getLanguagesList(){
		languagesListApi(this.artFrom).then((res) => {
	  		this.languagesList = res.data.list;
		}).catch((err)=>{

			this.$Message.error(err.msg);
		})
	  
	  },
	   getCurrentLanguage() {
	        // 返回当前语言标识，例如 'en' 或 'zh'
	        return this.$i18n.locale;
     },

	  getCountryList(){
		  let lang = this.getCurrentLanguage()
		  this.artFrom.lang = lang
	  		countryListApi(this.artFrom).then((res) => {
	  		this.countryList = res.data.list;
	  		}).catch((err)=>{
	  
	  			this.$Message.error(err.msg);
	  		})
	  
	  },
	  getTagsListApi(){
	  		tagsListApi().then((res) => {
	  		this.tagsList = res.data.list;
	  		}).catch((err)=>{
	  
	  			this.$Message.error(err.msg);
	  		})
	  
	  },
	  getStatesList(){
	  		statesListApi(this.artFrom).then((res) => {
	  		this.statesList = res.data.list;
	  		}).catch((err)=>{
	  
	  			this.$Message.error(err.msg);
	  		})
	  
	  },
    // 删除
    del(row, tit, num) {
		let delfromData = {
		title: $t('page.customer.remove_cusomer'),
		  num: num,
		  url: `store_customer/del/${row.id}`,
		  method: "DELETE",
		  ids: "",
			info:$t('page.customer.remove_customer_confirm'),
		};
      // let delfromData = {
      //   title: tit,
      //   num: num,
      //   url: `store_customer/del/${row.id}`,
      //   method: "DELETE",
      //   ids: '',
      // };
      this.$modalSure(delfromData)
          .then((res) => {
            this.$Message.success(res.msg);
            this.tableList.splice(num, 1);
            if (!this.tableList.length) {
              this.artFrom.page =
                  this.artFrom.page == 1 ? 1 : this.artFrom.page - 1;
            }
            this.getDataList();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
    },
	// 原生 JS 格式化
	formatTimeNative(timestamp) {
	      const date = new Date(timestamp);
	      const year = date.getFullYear();
	      const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
	      const day = String(date.getDate()).padStart(2, '0');
	      const hours = String(date.getHours()).padStart(2, '0');
	      const minutes = String(date.getMinutes()).padStart(2, '0');
	      
	      return `${year}-${month}-${day} ${hours}:${minutes}`;
	},
    addAttr() {
      this.$refs.addattr.ids = 0;
      this.$refs.addattr.modal = true;
    },
    // 编辑
    edit(row) {
      this.$refs.addattr.ids = row.id;
	  // alert(123);
      this.$refs.addattr.modal = true;
      this.$refs.addattr.getIofo(row);
    },
    // 列表；
    getDataList() {
      this.loading = true;
      storeCustomerListApi(this.artFrom)
          .then((res) => {
            let data = res.data;
            this.tableList = data.list
            this.total = res.data.count;
            this.loading = false;
          })
          .catch((res) => {
            this.loading = false;
            this.$Message.error(res.msg);
          });
    },
    pageChange(status) {
      this.artFrom.page = status;
      this.getDataList();
    },
    // 表格搜索
    userSearchs() {
      this.artFrom.page = 1;
      this.getDataList();
    },
    async exportStock() {
          try {
            this.exportLoading = true;
            let res; // 在函数作用域声明
            // 1. 调用导出接口获取文件信息
            res = await exportStoreCustomerList(this.artFrom);
            // 2. 检查响应是否成功
            if (res.code !== 0) {
              throw new Error(res.msg || '导出失败');
            }

            // 3. 获取文件信息
            const fileInfo = res.data;

            // 4. 使用文件URL下载文件
            await this.downloadFile(fileInfo);

            // 5. 显示成功消息
            Message.success('导出成功，文件已开始下载');

          } catch (error) {
            // 错误处理
            Message.error(error.message || '导出失败，请重试');
            console.error('导出错误:', error);
          } finally {
            this.exportLoading = false;
          }
    },
	async downloadFile(fileInfo) {
	      try {
	        // 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
	        // const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
	        const downloadUrl = fileInfo.exports_url;
			 // 2. 创建隐藏的<a>标签触发下载
			const link = document.createElement('a');
			link.href = downloadUrl;
			        
			// 从URL中提取文件名，或自定义文件名
			const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
			link.download = fileName; // 设置下载文件名
			        
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
	      } catch (error) {
	        console.error('文件下载错误:', error);
	        throw new Error('文件下载失败: ' + error.message);
	      }
	},
  },
};
</script>

<style scoped lang="stylus">
.ivu-mts{
  /deep/.ivu-card-body{
    padding-bottom 0!important
    padding-top 24px!important
  }
}
.input-add {
  width: 250px;
  margin-right:14px;
}
/deep/.ivu-table-header {
  // overflow visible
}

/deep/.ivu-table th {
  overflow: visible;
}

/deep/.select-item:hover {
  background-color: #f3f3f3;
}

/deep/.select-on {
  display: block;
}

/deep/.select-item.on {
  // background: #f3f3f3;
}
</style>